<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="dialog"
    :close-on-click-modal="false"
    title="商品交叉"
    append-to-body
    width="95%"
    @close="cancel"
  >
    <div class="app-container">
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchUpdate">保存</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchValidate">批量校验</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doSubmitBPMS">提交审核</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="downloadExcelTemplate(parent.$route.name, 1)">下载导入模板</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="exportTempDataExcel(data, parent.$route.name)">导出</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchCreate">保存</el-button>
      <el-button class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doReadInfo">获取Item信息</el-button>
      <div v-if="createFlag === true" style="margin-bottom:5px;">
        <el-form :inline="true" size="small" label-width="auto">
          <el-form-item label="主次商品号：">
            <el-input v-model="itemNbrTxt" placeholder="注：主次商品号以英文半角逗号分隔，一行为一对交叉商品，多对交叉商品需换行" rows="5" type="textarea" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="采购ID：">
            <el-select v-model="buyerId" style="width: 280px;">
              <el-option v-for="bid in buyerList" :key="bid" :label="bid" :value="bid" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="data" stripe size="small" border :height="tableHeight" style="width: 100%;" @header-dragend="colChange">
        <el-table-column type="index" align="center" fixed width="55" label="序号" />
        <el-table-column v-if="createFlag === true" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">移除该项</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="createFlag === false" label="校验信息">
          <template slot-scope="scope">
            <!--<el-popover
              v-if="scope.row.errorMsg && JSON.parse(scope.row.errorMsg).length > 0"
              placement="bottom"
              title="校验信息"
              trigger="click"
            >
              <div style="height:400px;overflow:auto;">
                <div v-for="(msg,index) in JSON.parse(scope.row.errorMsg)" :key="index" :index="index">
                  <span>{{ (index + 1) + '.' + msg }}</span>
                </div>
              </div>
              <el-button slot="reference" size="mini" type="text" style="color:#fc1111">点击查看</el-button>
            </el-popover>-->
            <validateMsg :item="scope.row" :type="3" />
          </template>
        </el-table-column>
        <el-table-column label="作业类型" prop="workOption" :width="colWidths.workOption">
          <template slot-scope="scope">
            <el-select v-model="scope.row.workOption" class="filter-item" :width="colWidths.workOption" @change="workOptionChange">
              <el-option key="1" label="连交叉" value="1" />
              <el-option key="2" label="解交叉" value="2" />
              <el-option key="3" label="主次调换" value="3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="主商品" prop="mainItemNbr" :width="colWidths.mainItemNbr" />
        <el-table-column label="次商品" prop="secondItemNbr" :width="colWidths.secondItemNbr" />
        <el-table-column label="主商品状态" prop="mainItemStatus" :width="colWidths.mainItemStatus" />
        <el-table-column label="次商品状态" prop="secondItemStatus" :width="colWidths.secondItemStatus" />
        <el-table-column label="主商品类型" prop="mainItemType" :width="colWidths.mainItemType" />
        <el-table-column label="次商品类型" prop="secondItemType" :width="colWidths.secondItemType" />
        <el-table-column label="主商品发送trait" prop="mainItemSendTrait" :width="colWidths.mainItemSendTrait" />
        <el-table-column label="主商品不发送trait" prop="mainItemOmitSendTrait" :width="colWidths.mainItemOmitSendTrait" />
        <el-table-column label="次商品发送trait" prop="secondItemSendTrait" :width="colWidths.secondItemSendTrait" />
        <el-table-column label="次商品不发送trait" prop="secondItemOmitSendTrait" :width="colWidths.secondItemOmitSendTrait" />
        <el-table-column label="主商品部门" prop="mainItemDept" :width="colWidths.mainItemDept" />
        <el-table-column label="次商品部门" prop="secondItemDept" :width="colWidths.secondItemDept" />
        <el-table-column label="主商品说明1" prop="mainItem1Desc" :width="colWidths.mainItem1Desc" />
        <el-table-column label="次商品说明1" prop="secondItem1Desc" :width="colWidths.secondItem1Desc" />
        <el-table-column label="主商品UPC" prop="mainItemUpc" :width="colWidths.mainItemUpc" />
        <el-table-column label="次商品UPC" prop="secondItemUpc" :width="colWidths.secondItemUpc" />
        <el-table-column label="主商品生效日期" prop="mainItemOrdEffDate" :width="colWidths.mainItemOrdEffDate" />
        <el-table-column label="次商品交叉" prop="secondItemCross" :width="colWidths.secondItemCross" />
      </el-table>
    </div>
    <urgentForm ref="urgentForm" :parent="parent" />
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { parseTime } from '@/utils/index'
import { batchUpdateItem, batchCreateIXIUItem, queryIXIUItemInfo, batchValidate, queryList } from '@/api/change-item'
import urgentForm from './urgent'
import { exportTempDataExcel, downloadExcelTemplate } from '@/utils/item'
import initTable from '@/utils/initTable'
import validateMsg from '@/views/part/validateMsg'

export default {
  components: { urgentForm, validateMsg },
  mixins: [initTable],
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      data: [],
      loading: false,
      tableHeight: window.innerHeight * 0.7,
      createFlag: false,
      itemNbrTxt: '',
      buyerList: [],
      buyerId: ''
    }
  },
  methods: {
    exportTempDataExcel,
    downloadExcelTemplate,
    cancel() {
      this.data = []
      this.itemNbrTxt = ''
      this.buyerList = []
      this.buyerId = ''
    },
    // 修改保存触发
    doBatchUpdate() {
      this.$confirm('是否变更该 ' + this.data.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const val = []
        this.data.forEach(item => {
          item.changeTime = parseTime(new Date())
          val.push({ id: item.id, itemInfo: JSON.stringify(item) })
        })
        batchUpdateItem(val).then(() => {
          Message({
            message: '变更成功。',
            type: 'success',
            duration: 3 * 1000
          })
          this.parent.toQuery()
          this.loading = false
        }, (error) => {
          console.log(error)
          this.loading = false
        })
      })
    },
    // 删除一行
    deleteRow(index) {
      this.data.splice(index, 1)
    },
    // 新增保存触发
    doBatchCreate() {
      if (this.data.length < 1) {
        Message({
          message: '请编辑需要新增的Item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('是否新增该 ' + this.data.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const val = []
          this.data.forEach(item => {
            item.changeTime = parseTime(new Date())
            val.push({ id: '', buyerId: this.buyerId, itemInfo: JSON.stringify(item) })
          })
          batchCreateIXIUItem(val).then(() => {
            Message({
              message: '新增成功。',
              type: 'success',
              duration: 3 * 1000
            })
            this.parent.toQuery()
            this.loading = false
            this.dialog = false
          }, (error) => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 读取数据
    doReadInfo() {
      if (this.createFlag === true && (!this.itemNbrTxt || this.itemNbrTxt === '')) {
        Message({
          message: '请编辑需要新增的Item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else if (this.itemNbrTxt.length > 1000) {
        Message({
          message: '所需获取的信息过多，请使用Excel导入方式进行操作。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.loading = true
        let _itemNbrTxt = this.itemNbrTxt.trim() // 去掉两头空格
        _itemNbrTxt = _itemNbrTxt.replace(/[\n\r\s]/g, '-')
        const itemArray = _itemNbrTxt.split('-')
        const sourceData = []
        for (let i = 0; i < this.data.length; i++) {
          sourceData.push(this.data[i])
        }
        itemArray.forEach(_itemNbr => {
          if (_itemNbr && _itemNbr !== '') {
            const itemArray2 = _itemNbr.trim().split(',')
            if (itemArray2[0] && itemArray2[1]) {
              if (itemArray2[0] === itemArray2[1]) {
                Message({
                  message: '填写的主次商品一致：' + itemArray2[1],
                  type: 'warning',
                  duration: 3 * 1000
                })
              } else {
                this.data.push({ mainItemNbr: itemArray2[0], secondItemNbr: itemArray2[1] })
              }
            } else {
              Message({
                message: '单行数据必须包含交叉商品的两个商品号。',
                type: 'error',
                duration: 3 * 1000
              })
            }
          }
        })
        const itemNbrs = []
        this.data.forEach(item => {
          itemNbrs.push(item.mainItemNbr)
          itemNbrs.push(item.secondItemNbr)
          item.initMainDataFlag = 'N'
          item.initSecondDataFlag = 'N'
          this.$set(this.data, item)
        })
        queryIXIUItemInfo(itemNbrs).then(res => {
          if (res && res.itemInfoList) {
            res.itemInfoList.forEach(dbItem => {
              for (let i = 0; i < this.data.length; i++) {
                const obj = this.data[i]
                if (this.data[i].mainItemNbr.toString() === dbItem.itemNbr.toString()) {
                  obj.mainItemStatus = dbItem.itemStatusCode
                  obj.mainItemType = dbItem.itemTypeCode
                  obj.mainItemDept = dbItem.deptNbr
                  obj.mainItem1Desc = dbItem.item1Desc
                  obj.mainItemUpc = dbItem.upcNbr
                  obj.mainItemOrdEffDate = dbItem.itemOrdEffDate
                  if (res.traitList) { // 发送区域
                    const s_trait = []
                    const o_trait = []
                    res.traitList.forEach(trait => {
                      if (this.data[i].mainItemNbr.toString() === trait.itemNbr.toString()) {
                        if (trait.traitGroupType === 'S') {
                          s_trait.push(trait.traitNbr)
                        } else if (trait.traitGroupType === 'O') {
                          o_trait.push(trait.traitNbr)
                        }
                      }
                    })
                    obj.mainItemSendTrait = s_trait.join('O')
                    obj.mainItemOmitSendTrait = o_trait.join('O')
                  }
                  obj.initMainDataFlag = 'Y'
                }
                if (this.data[i].secondItemNbr.toString() === dbItem.itemNbr.toString()) {
                  const obj = this.data[i]
                  obj.secondItemStatus = dbItem.itemStatusCode
                  obj.secondItemType = dbItem.itemTypeCode
                  obj.secondItemDept = dbItem.deptNbr
                  obj.secondItem1Desc = dbItem.item1Desc
                  obj.secondItemUpc = dbItem.upcNbr
                  if (res.traitList) { // 发送区域
                    const s_trait = []
                    const o_trait = []
                    res.traitList.forEach(trait => {
                      if (this.data[i].secondItemNbr.toString() === trait.itemNbr.toString()) {
                        if (trait.traitGroupType === 'S') {
                          s_trait.push(trait.traitNbr)
                        } else if (trait.traitGroupType === 'O') {
                          o_trait.push(trait.traitNbr)
                        }
                      }
                    })
                    obj.secondItemSendTrait = s_trait.join('O')
                    obj.secondItemOmitSendTrait = o_trait.join('O')
                  }
                  if (res.refList) { // 次商品交叉关联
                    const refs = []
                    res.refList.forEach(ref => {
                      if (this.data[i].secondItemNbr.toString() === ref.itemNbr.toString()) {
                        refs.push(ref.refItemNbr)
                      }
                    })
                    obj.secondItemCross = refs.join(';')
                  }
                  obj.initSecondDataFlag = 'Y'
                }
                this.data.splice(i, 1, obj)
              }
            })
            const errorItems = []
            for (let i = this.data.length - 1; i >= 0; i--) {
              if (this.data[i].initMainDataFlag === 'N') {
                errorItems.push(this.data[i].mainItemNbr)
              }
              if (this.data[i].initSecondDataFlag === 'N') {
                errorItems.push(this.data[i].secondItemNbr)
              }
              if (this.data[i].initSecondDataFlag === 'N' || this.data[i].initMainDataFlag === 'N') {
                this.data.splice(i, 1)
              }
            }
            if (errorItems && errorItems.length > 0) {
              Message({
                message: '无效商品号：' + errorItems.join(','),
                type: 'warning',
                duration: 3 * 1000
              })
            }
          }
          this.loading = false
        }, (error) => {
          console.log(error)
          this.data = sourceData
          this.loading = false
        })
      }
    },
    // 批量提交审核前置
    doSubmitBPMS() {
      if (this.data.length < 1) {
        Message({
          message: '请选择需要提交审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        const _this = this.$refs.urgentForm
        _this.itemSize = this.data.length
        _this.changeType = this.parent.$route.name
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        _this.bpmsParam.auditBuyerId = this.parent.auditBuyerId
        _this.ids = ids
        _this.dialog = true
      }
    },
    // 作业类型变更触发
    async workOptionChange(val) {
      let more = false
      this.data.forEach(item => {
        if (item.workOption && val !== item.workOption) {
          more = true
        }
      })
      if (more === true) {
        this.$confirm('存在其他作业类型数据，是否覆盖？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (var i = 0; i < this.data.length; i++) {
            const _item = this.data[i]
            _item.workOption = val
            this.data.splice(i, 1, _item)
          }
        }, () => {
          for (var i = 0; i < this.data.length; i++) {
            const _item = this.data[i]
            if (!_item.workOption || _item.workOption === val) {
              _item.workOption = val
              this.data.splice(i, 1, _item)
            }
          }
        })
      } else {
        for (var i = 0; i < this.data.length; i++) {
          const _item = this.data[i]
          _item.workOption = val
          this.data.splice(i, 1, _item)
        }
      }
    },
    // 批量校验
    doBatchValidate() {
      this.$confirm('确认校验该 ' + this.data.length + ' 条item信息?', '校验数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        batchValidate({ ids: ids, changeType: this.parent.$route.name }).then(res => {
          queryList({ ids: ids, changeType: this.parent.$route.name }).then(dataList => {
            if (dataList) {
              const _data = []
              dataList.forEach(dataObj => {
                _data.push(JSON.parse(dataObj.itemInfo))
              })
              this.data = _data
            }
          })
          this.parent.toQuery()
          Message({
            message: '校验处理中，请稍后刷新页面进行查询。',
            type: 'success',
            duration: 3 * 1000
          })
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    }
  }
}
</script>

